import Vue from 'vue'
import VueRouter from 'vue-router'
import RouteRules from './modules/route-rules'
// progress bar
import NProgress from 'nprogress'
import '@/components/NProgress/nprogress.less'
import notification from 'ant-design-vue/es/notification'
import { setDocumentTitle } from '@/libs/utils'
import { i18nRender } from '@/locales'
import store from '@/store' // Vuex
import config from '@/config'

// hack router push callback
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => err);
}

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history', // history or hash
  base: process.env.BASE_URL,
  scrollBehavior: () => ({ y: 0 }),
  routes: RouteRules
});

// NProgress Configuration
NProgress.configure({ showSpinner: false })

// no redirect whitelist
const whiteList = ['login', 'register']
const loginRoute = 'login'
const defaultRoutePath = '/dashboard/workplace'

//路由拦截器
router.beforeEach((to, from, next) => {
  NProgress.start(); // start progress bar
  // 设置页面title
  to.meta && to.meta.title && setDocumentTitle(`${i18nRender(to.meta.title)} - ${config.title}`)
  // 未登录
  if (!store.getters.token) {
    // 未登录,但在免登录白名单或该页面允许匿名访问,则直接进入
    if (whiteList.includes(to.name) || to.meta.AllowAnonymous) {
      return next()
    }
    return next({ name: loginRoute, query: { redirect: to.fullPath } })
  }
  // 已登录且要跳转的页面是登录页
  if (to.name === loginRoute) {
    return next({ path: defaultRoutePath }) // 跳转到主页
  }
  // check login user.permissions is null
  if (store.getters.asyncRoutes.length !== 0) {
    return next();
  }
  // generate dynamic router
  store.dispatch('permission/generateRoutes').then(() => {
    // 动态添加可访问路由表
    const asyncRoutes = store.getters.asyncRoutes;
    asyncRoutes.forEach(item => router.addRoute(item));
    // 请求带有 redirect 重定向时，登录自动重定向到该地址
    const redirect = decodeURIComponent(from.query.redirect || to.path)
    if (to.path === redirect) {
      // set the replace: true so the navigation will not leave a history record
      return next({ ...to, replace: true })
    }
    // 跳转到目的路由
    return next({ path: redirect })
  }).catch(() => {
    notification.error({ message: '错误', description: '请求用户权限失败，请重试' })
    // 失败时，获取用户信息失败时，调用登出，来清空历史保留信息
    store.dispatch('Logout').finally(() => {
      return next({ name: loginRoute, query: { redirect: to.fullPath } })
    })
  })
  // if current page is login will not trigger afterEach hook, so manually handle it
  // NProgress.done()

});

router.afterEach(() => {
  NProgress.done() // finish progress bar
  window.scrollTo(0, 0)
});


export default router